/**
 * author:Administrator
 * date:2016/2/25
 * desc: 用户申请的 coupon
 */

'use strict';

let Repo = require('./CouponLogRepo.js');
let FormatDate = require('../../../infrastructure/appUtil/FormatDate.js');
let DomainModel = require('../../../lib/DomainModel.js');
let events = require('../../saga/domainEvent.js');

let STATUS_ENUM = {
  created: 'created',                 //0,    // 等待系统确认(start)
  //couponReserved: 'couponReserved', //1,    // 系统已确认数量足够
  recall: 'recall',                   //2,    // 存货不足(end)
  notUsed: 'notUsed',                 //0,    // 未使用
  used: 'used',                       //1,    // 已使用
};

class CouponLog extends DomainModel {

  constructor() {
    super();
  }

  /**
   * 新建 一个当前对象的实例
   * @param pojo, key:
   */
  static freshNew(pojo) {
    let item = new CouponLog();
    item.customerId = pojo.customerId;
    item.couponId = pojo.couponId;
    item.money = pojo.money;
    item.status = STATUS_ENUM.created;
    item.createdAt = FormatDate.unixTimestamp();
    return item;
  }

  /**
   * 从数据库中读取，re-constructor an obj
   * @param pojo
   */
  static rebuild(pojo) {
    let item = new CouponLog();
    let keys = Object.keys(pojo);
    for (let key of keys) {
      item[key] = pojo[key];
    }
    return item;
  }

  * store(sagaId) {
    let isNew = !this.id;
    yield Repo.store(this);
    if (isNew) {
      this.pubDomainEvent(new events.CouponApplied(sagaId, this));
    }
  }

  * couponReserved(sagaId) {
    let where = {id: this.id, status: STATUS_ENUM.created};
    let updateAttr = {status: STATUS_ENUM.notUsed};
    let isOk = yield Repo.update(where, updateAttr);
    return isOk;
  }

  * recall(sagaId) {
    let where = {id: this.id, status: STATUS_ENUM.created};
    let updateAttr = {status: STATUS_ENUM.recall};
    yield Repo.update(where, updateAttr);
  }

  isUsed() {
    return this.status == STATUS_ENUM.used;
  }

  * useSelf(order, sagaId) {
    let where = {id: this.id, status: STATUS_ENUM.notUsed};
    let updateAttr = {status: STATUS_ENUM.used};
    let isOk = yield Repo.update(where, updateAttr);
    if (isOk) {
      this.status = STATUS_ENUM.used;
      this.pubDomainEvent(new events.CouponLogUsed(sagaId, {order: order, couponLog: this}));
    }
    return isOk;
  }

  * unUseSelf(sagaId) {
    let where = {id: this.id, status: STATUS_ENUM.used};
    let updateAttr = {status: STATUS_ENUM.notUsed};
    yield Repo.update(where, updateAttr);
  }
}

module.exports = CouponLog;